package com.ruoyi.system.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.system.domain.Post;
import com.ruoyi.system.domain.Reply;
import com.ruoyi.system.mapper.PostMapper;
import com.ruoyi.system.mapper.ReplyMapper;
import com.ruoyi.system.service.PostService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional
public class PostServiceImpl implements PostService {

    @Resource
    private PostMapper postMapper;

    @Resource
    private ReplyMapper replyMapper;


    @Override
    public int addPost(Post post) {
        return postMapper.insert(post);
    }

    @Override
    public Post getPostById(Integer id) {
        Post post = postMapper.selectById(id);
        if (post != null) {
            List<Reply> replies = replyMapper.selectRepliesByPostId(id);
            post.setReplies(replies);
        }
        return post;
    }

    @Override
    public List<Post> getAllPosts() {
        return postMapper.selectAll();
    }

    @Override
    public boolean updateClickCount(Integer id) {
        Post post = postMapper.selectById(id);
        if (post != null) {
            return postMapper.updateClickCount(id, post.getClickCount() + 1) > 0;
        }
        return false;
    }

    @Override
    public PageInfo<Post> getPostsByPage(int pageNum, int pageSize) {
        // 开启分页
        PageHelper.startPage(pageNum, pageSize);
        List<Post> posts = postMapper.selectPostsByPage((pageNum - 1) * pageSize, pageSize);
        return new PageInfo<>(posts);
    }
}